package com.ciwong.epaper.modules.reciteWords.util.download;

import android.content.Context;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.db.DBCallBack;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.reciteWords.bean.ReciteWordBookBean;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.DBManagerAsyn;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.DBWordBookStateManagerAsyn;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.List;

public class WordBookDownloadManager {
    private static String TAG = "WordDownloadManager";
    private static final String deserializeSuccessStr = "反序列化成功";
    private static final String deserializeErrorStr = "获取本地Modules失败";
    private static String insertDBSuccessStr = "插入数据库成功";
    private static String insertDBFailStr = "插入数据库失败";

    private WordBookDownloadManager() {
    }

    public static void downLoadFile(final Context context, final String bookId, final String url, final DownloadCallBack downloadCallBack) {

        if (bookId == null || url == null) return;
        //注意为了区分 用了两个bookid作为键
        final String bookId_ = bookId + bookId;
        checkWordBookIsExist(bookId_, new CallBack() {
            @Override
            public void result(int code) {
                if (code == -1 || url.hashCode() != code) {//当数据库中不存在记录或者记录hashcode 不一致
                    downLoadFileChecked(context, bookId_, url, downloadCallBack);
                } else {//当数据库中存在记录
                    checkTableDateIsExist(bookId, new CallBack() {
                        @Override
                        public void result(int code) {
                            if (code == 2) {//表示数据表已存在，数据也存在
                                if (downloadCallBack != null)
                                    downloadCallBack.downloadAlready();
                                CWLog.e(TAG, "checkWordBookIsExistORNoData 书籍列表已存在");
                            } else {//其他状态重新下载
                                downLoadFileChecked(context, bookId_, url, downloadCallBack);
                            }
                        }
                    });
                }
            }
        });

    }

    /**
     * 暂停下载
     *
     * @param info
     */
    public static void pauseTask(DownLoadInfo info) {
        BaseDownLoad.getInstance().pauseTask(info);
    }

    /**
     * 检测过 单词书不存在
     *
     * @param bookId
     * @param url
     * @param downloadCallBack
     */
    private static void downLoadFileChecked(Context context, String bookId, String url, DownloadCallBack downloadCallBack) {
        try {
            if (downloadCallBack != null)
                downloadCallBack.downloadStart();

            DownLoadInfo tempInfo = new DownLoadInfo();
            tempInfo.setSavePath(getDownloadPathByBookId(bookId));
            DownLoadInfo info = BaseDownLoad.getInstance().getCurrentBean(tempInfo);

            // 不存在下载队列中添加到下载队列, 失败了重新请求地址重下
            if (info == null || info.getStatus() == DownloadStatus.STATUS_FAILED
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_SDISFULL
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                downloadNewFile(context, bookId, url);
            } else {
                CWLog.e(TAG, "downloadNewFile");
                //解决 弱网情况下 下载没有回调问题，把任务挂起 后继续下载
                BaseDownLoad.getInstance().pauseTask(info);
                BaseDownLoad.getInstance().resumeTask(info);
                // 下载状态
                switch (info.getStatus()) {
                    case DownloadStatus.STATUS_PAUSE:
                        BaseDownLoad.getInstance().resumeTask(info);
                        break;
                    case DownloadStatus.STATUS_FAILED:
                    case DownloadStatus.STATUS_FAILED_SDISFULL:
                    case DownloadStatus.STATUS_FAILED_UNZIP:
                        BaseDownLoad.getInstance().addTask(info);
                        break;
                    case DownloadStatus.STATUS_LOADING:
                    case DownloadStatus.STATUS_DOWNLOADING:
                        break;
                    case DownloadStatus.STATUS_UPZIPING:
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            if (downloadCallBack != null)
                downloadCallBack.downloadStart();
        }
    }

    private static void downloadNewFile(Context context, String bookId, String url) {
        CWLog.e(TAG, "downloadNewFile");
        DownLoadInfo downLoadInfo = new DownLoadInfo();
        downLoadInfo.setBookId(bookId);
        downLoadInfo.setUrl(url);
        downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(context, url));
        downLoadInfo.setStatus(DownloadStatus.STATUS_LOADING);
        BaseDownLoad.getInstance().addTask(downLoadInfo);
    }


    private static String getDownloadPathByBookId(String bookId) {
        DownLoadInfo info = DownLoadDB
                .queryDownloadInfoByDoubleBookId(bookId);
        if (info == null) {
            return "";
        }
        return info.getSavePath();
    }


    public static void getWordBookList(Context context, String path, final DeserializeCallBack deserializeCallBack) {
        try {
            EpaperDao.getInstance().getSerializableObjects(path, ReciteWordBookBean.class,
                    new BaseExtCallBack(context, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, deserializeErrorStr, "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError(deserializeErrorStr);
                            CWLog.d(TAG, deserializeErrorStr + data.toString());
                            if (deserializeCallBack != null)
                                deserializeCallBack.deserializeFail(data);
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            if (deserializeCallBack != null)
                                deserializeCallBack.deserializeFail(data);
                            FeedbackUtil.getInstance().addFeedbackLog(
                                    FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, deserializeErrorStr, "本地读资源", true);
                            ToastUtil.INSTANCE.toastCenterError(deserializeErrorStr);
                            CWLog.d(TAG, deserializeErrorStr + errorCode + " : " + data.toString());
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void success(Object data) {
                            if (deserializeCallBack != null)
                                deserializeCallBack.deserializesuccess(deserializeSuccessStr);
                            try {
                                final ReciteWordBookBean modules = (ReciteWordBookBean) data;
                                CWLog.d(TAG, "读取本地资源成功" + modules.toString());
                                instertWord2Table(modules.getVersionId() + "", modules.getWordList(), deserializeCallBack);
                            } catch (Exception e) {
                                e.getStackTrace();
                                if (deserializeCallBack != null)
                                    deserializeCallBack.insertDBFail(data);
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            if (deserializeCallBack != null)
                deserializeCallBack.deserializeFail(e.getMessage());
        }
    }

    public interface CallBack {
        void result(int code);
    }

    private static void checkWordBookIsExist(String bookId, final CallBack callBack) {
        DBWordBookStateManagerAsyn.getInstance().queryWordBookUrlHashCodeAsyn(bookId, new DBCallBack() {
            @Override
            public void dbResult(Object data) {
                if (callBack != null)
                    callBack.result((Integer) data);

            }
        });
    }

    private static void checkTableDateIsExist(String bookId, final CallBack callBack) {
        DBManagerAsyn.getInstance().executeCheckTableAndData(bookId, new DBCallBack() {
            @Override
            public void dbResult(Object data) {
                if (callBack != null)
                    callBack.result((Integer) data);
            }
        });
    }

    /**
     * 把单词插入数据库
     *
     * @param versionId
     * @param wordDetails
     * @param deserializeCallBack
     */

    private static void instertWord2Table(final String versionId, List<WordDetail> wordDetails, final DeserializeCallBack deserializeCallBack) {

        if (DBManagerAsyn.getInstance().checkTableIsExist(versionId)) {
            DBManagerAsyn.getInstance().dropTable(versionId);
            DBManagerAsyn.getInstance().creatTable(versionId);
        }
        DBManagerAsyn.getInstance().addAsynIfNoExist(versionId, wordDetails, new DBCallBack() {
            @Override
            public void dbResult(Object data) {
                CWLog.d(TAG, "插入数据库成功" + data.toString());
                boolean result = (Boolean) data;
                if (deserializeCallBack != null) {
                    if (!result) {
                        deserializeCallBack.insertDBFail(insertDBFailStr);
                    } else {
                        deserializeCallBack.insertDBsuccess(insertDBSuccessStr);
                    }
                }
              /*  DBManagerAsyn.getInstance().queryAllAsny(versionId, new DBCallBack() {
                    @Override
                    public void dbResult(Object data) {
                        List<WordDetail> list = (List<WordDetail>) data;
                        CWLog.d(TAG, "查询数据库成功" + list.size());

                    }
                });*/

            }
        });
    }

    public static String getUpZipFilePath(String savePath) {
        String fileName = savePath.substring(savePath.lastIndexOf("/"));
        String packageDir = ESystem.getPackagesReciteWord(fileName.substring(0, fileName.indexOf(".")));
        return packageDir;
    }

    public static void deleteReciteWordBookFile(String savePath) {
        BaseDownLoad.getInstance().deleteReciteWordBookFile(savePath);
    }

}
